#!coding:utf-8
'''
Created on Oct 17, 2012

@author: join
'''
from lottery_terminal.service.lotteryservice.baseService import BaseLottery
from lottery_terminal.models import ThreeD, Trade
from lottery_terminal.common import utils
import datetime

class ThreaDLottery(BaseLottery):
    '''
    福彩3D彩票业务模块，所有福彩3D的业务操作在此模块中完成
    '''
    def __init__(self):
        BaseLottery.__init__(self,'05')
        self.ticketobj = ThreeD
        self.fs_dict = {'1':'danshi','2':'fushi','3':'baohao'}
        self.wanfa_dict = {'1':'zhixuan3','2':'zuxuan3','3':'zuxuan6'}
        self.validityday = 59
    
    def handle_codes(self,ticket_infos,tradetime,sd_batchid):
        '''处理3D彩票号码，包括直选3单式，组选3单式，组选6单式，直选3复式，(直选3包号，不提供)，组选3包号，组选6包号'''
        result = {}
        code_zhixuan3_danshi = [] #2,8,4#1#1#1#2 => 2,8,4:1:1:1
#        code_zhixuan3_fushi = [] #25,8,4#1#2#1#2 => 25,8,4:1:2:1
        code_zuxuan3_danshi = [] #5,3,3#2#1#1#2 => 5,3,3:2:1:1
#        code_zuxuan3_baohao = [] #5,6,7#2#3#1#12
        code_zuxuan6_danshi = [] #5,3,8#3#1#1#2 => 5,3,8:3:1:1
#        code_zuxuan6_baohao = [] #2,3,4,5,6,7#3#3#1#40 => 234567:3:3:1
        code_fuza = []
        
        codes_handled = [] #用来向第三方接口进行交互的号码格式
        num_list = [] #打印到彩票上的号码组信息
        trades = [] #本次购买彩票的所有交易
        
        ticket_codes = ticket_infos['codes'] #前台传过来的彩票号码信息组
        period = ticket_infos['period']
        
        batchid = utils.generate_batchid()
        hmid = batchid
        index = 0
        self.validitytime = period.awardtime + datetime.timedelta(days=self.validityday)
        
        #将前台传过来的号码分类，方便打印上的控制
        for code in ticket_codes:
            ccodes = code.split('#')
            if ccodes[2] == '1': #单式
                if ccodes[1] == '1': #直选3
                    code_zhixuan3_danshi.append(code)
                elif ccodes[1] == '2':
                    code_zuxuan3_danshi.append(code)
                elif ccodes[1] == '3':
                    code_zuxuan6_danshi.append(code)
            else: #复杂
                code_fuza.append(code)
#                code_zhixuan3_fushi.append(code)
#            elif ccodes[2] == '3': #包号
#                if ccodes[1] == '2': #组选3
#                    code_zuxuan3_baohao.append(code)
#                elif ccodes[1] == '3': #直选6
#                    code_zuxuan6_baohao.append(code)
#            code = ':'.join(ccodes[:-1])
#            codes_handled.append('%s-%s_%s'%(batchid,(index+1),code))
        #单式票叠加，目的分类排序，使得打印有序
        code_danshi=code_zhixuan3_danshi + code_zuxuan3_danshi + code_zuxuan6_danshi
        
        for fuza_code in code_fuza:
            index += 1
            codes = fuza_code.split('#')
            #对每张彩票都记录流水号，以方便做是否中奖比对
            code = ':'.join(codes[:-1])
            businessid = '%s-%s' % (hmid,index)
            codes_handled.append('%s_%s'%(businessid,code))
            
            tradeamount = int(codes[-1])
            ticket_amount = int(codes[-2])
      
            batchid = '%s' % (int(batchid)+1)
            trade = Trade(tradeType=1,tradeTicketType=self.lotterycode_db,tradeMethod=ticket_infos['buymethod'],tradeAmount=tradeamount,period=period,
                    accountid=ticket_infos['account'],tradeTime=tradetime,status=0,prizeType=ticket_infos['prizeType'],batchid=batchid,desc=sd_batchid) #创建一条交易记录，状态为交易中
            trade.save()
            trades.append(trade)
            num_list.append({'batchid':batchid,'num':['%s' % fuza_code.split('#')[0]],'fs':codes[2],'wanfa':codes[1],'tradeamount':tradeamount,'beishu':ticket_amount})
            ThreeD.objects.create(lotteryNumber=':'.join(fuza_code.split('#')[:-1]),ticketamount=ticket_amount,buytime=tradetime,
                          validitytime=self.validitytime,status=0,buymoney=tradeamount,tradeId=trade,businessid=businessid)  #创建彩票记录到数据库
#            
        #单式
        ds_count = 0 #每5注保存为一个交易
        tradeamount = 0
        for ds_code in code_danshi:
            index += 1
            codes = ds_code.split('#')
            #对每张彩票都记录流水号，以方便做是否中奖比对
            code = ':'.join(codes[:-1])
            businessid = '%s-%s' % (hmid,index)
            codes_handled.append('%s_%s'%(businessid,code))
            
            ticket_amount = int(codes[-2])
            if ds_count%5 == 0:
                tradeamount = sum([int(t.split('#')[-1]) for t in code_danshi[ds_count:ds_count+5]])
                batchid = '%s' % (int(batchid)+1)
                num_list.append({'batchid':batchid,'num':['%s'%t.split('#')[0] for t in code_danshi[ds_count:ds_count+5]],
                                 'fs':codes[2],'wanfa':codes[1],'tradeamount':tradeamount,'beishu':ticket_amount})
                trade = Trade(tradeType=1,tradeTicketType=self.lotterycode_db,tradeMethod=ticket_infos['buymethod'],tradeAmount=tradeamount,period=period,
                              accountid=ticket_infos['account'],tradeTime=tradetime,status=0,prizeType=ticket_infos['prizeType'],batchid=batchid,desc=sd_batchid) #创建一条交易记录，状态为交易中
                trade.save()
                trades.append(trade)
            
            ds_count += 1
            buy_money = int(codes[-1])
            ds_code = ':'.join(codes[:-1])
            ThreeD.objects.create(lotteryNumber=ds_code,ticketamount=ticket_amount,buytime=tradetime,
                validitytime=self.validitytime,status=0,buymoney=buy_money,tradeId=trade,businessid=businessid)  #创建彩票记录
        
        result['trades'] = trades
        result['codes_handled'] = codes_handled
        result['num_list'] = num_list
        return result